package com.google.code.p.restrpc.mon.web.server;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.google.code.p.restrpc.core.RpcServiceMetadata;
import com.google.code.p.restrpc.core.RpcServiceRepository;
import com.google.code.p.restrpc.core.async.AsyncServiceManagers;
import com.google.code.p.restrpc.spring.RpcServiceRemoteExporter;

public class ServerMonitor {
    
    public static final Map EMPTY_MAP = new HashMap(0);
    
    public Map serverStatus(Map parameters) {
        Map result = new HashMap();  
        result.put("registeredService",RpcServiceRepository.getInstance().size());
        result.put("queuedAsyncRequest",AsyncServiceManagers.getAsyncRpcManager().queuedSize());
        result.put("completedAsyncResult",AsyncServiceManagers.getAsyncRpcManager().completedSize());
        return result;
    }
    
    public Map remoteExporterSettings(Map parameters) {
        RpcServiceRemoteExporter instance = RpcServiceRemoteExporter.getInstance();
        if (null == instance) {
            return EMPTY_MAP;
        }
        
        Map result = new HashMap();
        result.put("protocal", instance.getProtocal());
        result.put("address", instance.getAddress());
        result.put("port", instance.getPort());
        result.put("context", instance.getContext());
        result.put("heartbeat", instance.getHeartbeat());
        result.put("weight", instance.getWeight());
        result.put("registryUrl", instance.getRegistryUrl());
        return result;
    }
    
    public String[] serviceNames(Map parameters) {
        return RpcServiceRepository.getInstance().getServiceNames();
    }
    
    public RpcServiceMetadata serviceMetadata(Map parameters) {
        String[] serviceNames = (String[]) parameters.get("serviceName");
        if (serviceNames == null || serviceNames.length == 0) {
            return null;
        }
        String serviceName = serviceNames[0];
        if (StringUtils.isEmpty(serviceName)) {
            return null;
        }
        
        return RpcServiceRepository.getInstance()
                                   .getRpcServiceMetadata(serviceName);
    }
    
}
